from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.schemas.waveup.wp_collection import WPCollectionListQueryReq, WpCollectionCreate
from app.models.waveup.wp_collection import WpCollection
from sqlalchemy import select

async def get_collection_list(session: Session, query: WPCollectionListQueryReq):
    """查询WaveUp藏品列表"""
    statement = select(WpCollection)
    if query.productIds:
        statement = statement.where(WpCollection.productId.in_(query.productIds))
    
    # 计算总数
    total = await session.execute(statement)
    total = len(total.scalars().all())

    # 分页查询
    statement = statement.offset((query.pageNo - 1) * query.pageSize).limit(query.pageSize)
    result = await session.execute(statement)

    return {
        "records": result.scalars().all(),
        "total": total,
        "pageNo": query.pageNo,
        "pageSize": query.pageSize
    }

async def create_collection(
    session: Session, collection_in: WpCollectionCreate
) -> WpCollection:
    """创建新藏品"""
    db_collection = WpCollection.model_validate(collection_in)
    session.add(db_collection)
    await session.commit()
    await session.refresh(db_collection)
    return db_collection

async def get_collection_by_product_id(
    session: Session, product_id: str
) -> WpCollection | None:
    """根据藏品ID查询藏品"""
    statement = select(WpCollection).where(WpCollection.productId == product_id)
    result = await session.execute(statement)
    return result.scalars().first()